{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# TF-IDF简单示例"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1. 定义数据和预处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'The', 'bed', 'cat', 'dog', 'face', 'my', 'on', 'sat'}"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "docA = \"The cat sat on my face\"\n",
    "docB = \"The dog sat on my bed\"\n",
    "\n",
    "bowA = docA.split(\" \")\n",
    "bowB = docB.split(\" \")\n",
    "#bowA\n",
    "\n",
    "wordSet = set(bowA).union(set(bowB))\n",
    "wordSet"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2. 统计词的频数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>The</th>\n",
       "      <th>bed</th>\n",
       "      <th>cat</th>\n",
       "      <th>dog</th>\n",
       "      <th>face</th>\n",
       "      <th>my</th>\n",
       "      <th>on</th>\n",
       "      <th>sat</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>0</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   The  bed  cat  dog  face  my  on  sat\n",
       "0    1    0    1    0     1   1   1    1\n",
       "1    1    1    0    1     0   1   1    1"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "wordCountA = dict.fromkeys(wordSet, 0)\n",
    "wordCountB = dict.fromkeys(wordSet, 0)\n",
    "\n",
    "for word in bowA:\n",
    "    wordCountA[word] += 1\n",
    "for word in bowB:\n",
    "    wordCountB[word] += 1\n",
    "    \n",
    "import pandas as pd\n",
    "pd.DataFrame([wordCountA, wordCountB])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3. 计算词频"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'The': 0.16666666666666666,\n",
       " 'bed': 0.0,\n",
       " 'cat': 0.16666666666666666,\n",
       " 'dog': 0.0,\n",
       " 'face': 0.16666666666666666,\n",
       " 'my': 0.16666666666666666,\n",
       " 'on': 0.16666666666666666,\n",
       " 'sat': 0.16666666666666666}"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 在每个文档里的词频计算\n",
    "def computeTF(wordCount, bow):\n",
    "    # 记录tf结果\n",
    "    tfDict = {}\n",
    "    bowCount = len(bow)\n",
    "    for word, count in wordCount.items():\n",
    "        tfDict[word] = count/float(bowCount)\n",
    "    return tfDict\n",
    "\n",
    "tfA = computeTF(wordCountA, bowA)\n",
    "tfB = computeTF(wordCountB, bowB)\n",
    "tfA"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4. 计算逆文档频率"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'The': 0.0,\n",
       " 'bed': 0.17609125905568124,\n",
       " 'cat': 0.17609125905568124,\n",
       " 'dog': 0.17609125905568124,\n",
       " 'face': 0.17609125905568124,\n",
       " 'my': 0.0,\n",
       " 'on': 0.0,\n",
       " 'sat': 0.0}"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 统一传入所有文档的wordCount字典\n",
    "def computeIDF(docList):\n",
    "    import math\n",
    "    idfDict = {}\n",
    "    N = len(docList)\n",
    "    \n",
    "    idfDict = dict.fromkeys(docList[0].keys(), 0)\n",
    "    \n",
    "    for doc in docList:\n",
    "        for word, count in doc.items():\n",
    "            if count > 0:\n",
    "                idfDict[word] += 1\n",
    "    for word, count in idfDict.items():\n",
    "        idfDict[word] = math.log10( (N+1)/float(count + 1) )\n",
    "    return idfDict\n",
    "\n",
    "idfs = computeIDF([wordCountA, wordCountB])\n",
    "idfs"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 5. 计算TF-IDF"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>The</th>\n",
       "      <th>bed</th>\n",
       "      <th>cat</th>\n",
       "      <th>dog</th>\n",
       "      <th>face</th>\n",
       "      <th>my</th>\n",
       "      <th>on</th>\n",
       "      <th>sat</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>0.0</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.029349</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.029349</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>0.0</td>\n",
       "      <td>0.029349</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.029349</td>\n",
       "      <td>0.000000</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "      <td>0.0</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   The       bed       cat       dog      face   my   on  sat\n",
       "0  0.0  0.000000  0.029349  0.000000  0.029349  0.0  0.0  0.0\n",
       "1  0.0  0.029349  0.000000  0.029349  0.000000  0.0  0.0  0.0"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def computeTFIDF(tf, idfs):\n",
    "    tfidf = {}\n",
    "    for word, tf in tf.items():\n",
    "        tfidf[word] = tf * idfs[word]\n",
    "    return tfidf\n",
    "\n",
    "tfidfA = computeTFIDF(tfA, idfs)\n",
    "tfidfB = computeTFIDF(tfB, idfs)\n",
    "pd.DataFrame([tfidfA, tfidfB])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
